//
//  LYWithdrawController.m
//  SelectCity
//
//  Created by liuyan on 2019/3/30.
//  Copyright © 2019年 liuyan. All rights reserved.
//

#import "LYWithdrawController.h"
#import "LYWithDrawLabelCell.h"
#import "LYWithDrawInputCell.h"
#import "LYWithdrawModel.h"
#import "ActionSheetStringPicker.h"
#import "WalletWithdrawalInstructionViewController.h"
#import "LYWithDrawListController.h"
#import "GeneralWebViewViewController.h"

@interface LYWithdrawController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) NSArray *titleArray;

@property (nonatomic, strong) LYWithdrawModel *model;

@property (nonatomic, strong) UITextField *moneyTF;
//有点
@property (nonatomic, assign) BOOL isHaveDian;
//第一个零
@property (nonatomic, assign) BOOL isFirstZero;

@property (nonatomic, strong) UILabel *handfeeLabel;
@property (nonatomic, strong) UILabel *arrivalLabel;

@end

@implementation LYWithdrawController

- (LYWithdrawModel *)model {
    if (!_model) {
        _model = [[LYWithdrawModel alloc] init];
        _model.accountType = @"支付宝";
        _model.handlingfee = @"0";
        _model.arrival = @"0";
    }
    return _model;
}
- (NSArray *)titleArray {
    if (!_titleArray) {
        _titleArray = @[@[@"账户余额", @"账户类型", @"提现账户", @"账户姓名", @"提现金额"], @[@"平台服务费", @"实际到账"]];
    }
    return _titleArray;
}
- (void)nextBtnTap {
    GeneralWebViewViewController *GWVC = [[GeneralWebViewViewController alloc] init];
    GWVC.showType = GeneralWebViewTypeOfWithdrawalInstructions;
    GWVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:GWVC animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGB(247, 247, 247);
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationItem.title = @"余额提现";
    UIButton *nextBtn = [UIToolsControl initButtonWithFrame:CGRectMake(WIDTH-50*Scale, HeightOfStatusBar+3*Scale, 50*Scale, 36) imageName:nil target:self action:@selector(nextBtnTap) title:@"提现说明" titleColor:THEMECOLOR_OF_ORANGE];
    nextBtn.titleLabel.font = Font(Font_15);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:nextBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-HeightOfStatusBarAndNavigationBar) style:UITableViewStyleGrouped];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.hidden = YES;
    self.tableview.showsVerticalScrollIndicator = NO;
    self.tableview.estimatedRowHeight = 0;
    self.tableview.estimatedSectionHeaderHeight = 0;
    self.tableview.estimatedSectionFooterHeight = 0;
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableview.backgroundColor = RGB(247, 247, 247);
    self.tableview.sectionIndexBackgroundColor = [UIColor clearColor];
    
    [self.tableview registerClass:[LYWithDrawLabelCell class] forCellReuseIdentifier:kCellIdentifier_LYWithDrawLabelCell];
    [self.tableview registerClass:[LYWithDrawInputCell class] forCellReuseIdentifier:kCellIdentifier_LYWithDrawInputCell];
    [self.view addSubview:self.tableview];
    
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 120)];
    self.tableview.tableFooterView = footer;
    
    UIButton *applybutton = [UIButton buttonWithType:UIButtonTypeCustom];
    applybutton.frame = CGRectMake( 40, 15, WIDTH-80, 40);
    applybutton.layer.cornerRadius = applybutton.height/2;
    applybutton.clipsToBounds = YES;
    applybutton.backgroundColor = [UIColor orangeColor];
    [applybutton setTitle:@"提交申请" forState:UIControlStateNormal];
    [applybutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    applybutton.titleLabel.font = [UIFont systemFontOfSize:14];
    [applybutton addTarget:self action:@selector(applybuttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [footer addSubview:applybutton];
    
    UIButton *checkbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    checkbutton.frame = CGRectMake((WIDTH - 140)/2, applybutton.bottom + 15, 140, 30);
    [checkbutton setTitle:@"（ 查看提现记录 ）" forState:UIControlStateNormal];
    [checkbutton setTitleColor:RGB(153, 153, 153) forState:UIControlStateNormal];
    checkbutton.titleLabel.font = [UIFont systemFontOfSize:14];
    [checkbutton addTarget:self action:@selector(checkBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [footer addSubview:checkbutton];
    
    [self requestAmountData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.titleArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *array = self.titleArray[section];
    return array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *array = self.titleArray[indexPath.section];
    if (indexPath.section == 0 && (indexPath.row == 2 || indexPath.row == 3 || indexPath.row == 4)) {
        LYWithDrawInputCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_LYWithDrawInputCell forIndexPath:indexPath];
        cell.title = array[indexPath.row];
         [cell.detailTF addTarget:self action:@selector(detailChange:) forControlEvents:UIControlEventEditingChanged];
        if (indexPath.row == 2) {
            cell.detailTF.placeholder = @"请输入提现账号";
            cell.detailTF.text = self.model.account;
        } else if (indexPath.row == 3) {
            cell.detailTF.placeholder = @"请输入账户姓名";
            cell.detailTF.text = self.model.accountName;
        } else {
            cell.detailTF.placeholder = @"请输入提现金额";
            cell.detailTF.text = self.model.withDrawMoney;
            cell.detailTF.delegate = self;
            self.moneyTF = cell.detailTF;
        }
        return cell;
    } else {
        LYWithDrawLabelCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_LYWithDrawLabelCell forIndexPath:indexPath];
        [cell setTitle:array[indexPath.row] isClicked:YES];
        if (indexPath.section == 0) {
            if (indexPath.row == 0) {
                 [cell setTitle:array[indexPath.row] isClicked:NO];
                cell.detailLabel.text = [NSString stringWithFormat:@"%@元",self.model.amount];
                cell.detailLabel.textColor = [UIColor orangeColor];
            } else {
                cell.detailLabel.text = self.model.accountType;
                cell.detailLabel.textColor = RGB(34, 34, 34);
            }
        } else {
            if (indexPath.row == 0) {
                cell.detailLabel.textColor = [UIColor redColor];
                NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:self.model.handlingfee];
                NSAttributedString *strq = [[NSAttributedString alloc] initWithString:@"元" attributes:@{NSForegroundColorAttributeName :RGB(34, 34, 34),NSFontAttributeName : [UIFont systemFontOfSize:13]}];
                [str appendAttributedString:strq];
                cell.detailLabel.attributedText = str;
                self.handfeeLabel = cell.detailLabel;
            } else {
                cell.detailLabel.textColor = [UIColor redColor];
                NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:self.model.arrival];
                NSAttributedString *strq = [[NSAttributedString alloc] initWithString:@"元" attributes:@{NSForegroundColorAttributeName :RGB(34, 34, 34),NSFontAttributeName : [UIFont systemFontOfSize:13]}];
                [str appendAttributedString:strq];
                cell.detailLabel.attributedText = str;
                self.arrivalLabel = cell.detailLabel;
            }
        }
        return cell;
    }
}
#pragma mark -- UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ((indexPath.section == 0) && (indexPath.row == 1)) {
        __weak typeof(self) weakSelf = self;
        NSNumber  *index = [NSNumber numberWithInteger:0];
        [ActionSheetStringPicker showPickerWithTitle:@"选择提现类型" rows:@[@[@"支付宝"]] initialSelection:@[index] doneBlock:^(ActionSheetStringPicker *picker, NSArray *selectedIndex, NSArray *selectedValue) {
            weakSelf.model.accountType = selectedValue.firstObject;
            [weakSelf.tableview reloadData];
        } cancelBlock:^(ActionSheetStringPicker *picker) {
            
        } origin:[UIApplication sharedApplication].keyWindow];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 1){
        return 8;
    }
    return 0.001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001f;
}

#pragma mark -- LoadData
- (void)requestAmountData{
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    __weak typeof(self) weakSelf = self;
    [BaseNetManager requestWithMethod:POST path:Wallet_getWithdrawConfig_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            weakSelf.tableview.hidden = NO;
            //钱包信息
            CGFloat amount = [responseObject[@"data"][@"amount"] floatValue];
            weakSelf.model.amount = [NSString stringWithFormat:@"%.2f",amount];
            weakSelf.model.amount = [UIToolsControl showAmount:weakSelf.model.amount];
            weakSelf.model.amount_min = [responseObject[@"data"][@"amount_min"] floatValue];
            weakSelf.model.amount_max = [responseObject[@"data"][@"amount_max"] floatValue];
            weakSelf.model.fee_rate = [responseObject[@"data"][@"fee_rate"] floatValue];
            weakSelf.model.fee_min = [responseObject[@"data"][@"fee_min"] floatValue];
            weakSelf.model.fee_max = [responseObject[@"data"][@"fee_max"] floatValue];
            [weakSelf.tableview reloadData];
        }else if ([responseObject[@"code"] integerValue] == 1400){
            SVPHUDError(responseObject[@"msg"]);
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}

#pragma mark --UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.moneyTF) {
        if ([textField.text rangeOfString:@"."].location==NSNotFound) {
            _isHaveDian = NO;
        }
        if ([textField.text rangeOfString:@"0"].location==NSNotFound) {
            _isFirstZero = NO;
        }
        if ([string length]>0){
            unichar single=[string characterAtIndex:0];//当前输入的字符
            if ((single >='0' && single<='9') || single=='.'){//数据格式正确
                if([textField.text length]==0){
                    if(single == '.'){
                        //首字母不能为小数点
                        return NO;
                    }
                    if (single == '0') {
                        _isFirstZero = YES;
                        return YES;
                    }
                }
                
                if (single=='.'){
                    if(!_isHaveDian)//text中还没有小数点
                    {
                        _isHaveDian=YES;
                        return YES;
                    }else{
                        return NO;
                    }
                }else if(single=='0'){
                    if ((_isFirstZero&&_isHaveDian)||(!_isFirstZero&&_isHaveDian)) {
                        //首位有0有.（0.01）或首位没0有.（10200.00）可输入两位数的0
                        if([textField.text isEqualToString:@"0.0"]){
                            return NO;
                        }
                        NSRange ran=[textField.text rangeOfString:@"."];
                        int tt=(int)(range.location-ran.location);
                        if (tt <= 2){
                            return YES;
                        }else{
                            return NO;
                        }
                    }else if (_isFirstZero&&!_isHaveDian){
                        //首位有0没.不能再输入0
                        return NO;
                    }else{
                        return YES;
                    }
                }else{
                    if (_isHaveDian){
                        //存在小数点，保留两位小数
                        NSRange ran=[textField.text rangeOfString:@"."];
                        int tt= (int)(range.location-ran.location);
                        if (tt <= 2){
                            return YES;
                        }else{
                            return NO;
                        }
                    }else if(_isFirstZero&&!_isHaveDian){
                        //首位有0没点
                        return NO;
                    }else{
                        return YES;
                    }
                }
            }else{
                //输入的数据格式不正确
                SVPHUDError(@"请输入正确的提现金额");
                return NO;
            }
        }else{
            return YES;
        }
    }
    return YES;
}

#pragma mark -- Action
- (void)detailChange:(UITextField *)textfiled{
    LYWithDrawInputCell *cell = (LYWithDrawInputCell *)textfiled.superview;
    NSIndexPath *indexpath = [self.tableview indexPathForCell:cell];
    if (indexpath.row == 2) {
        self.model.account = textfiled.text;
    }else if(indexpath.row == 3){
        self.model.accountName = textfiled.text;
    }else{
       NSString *money = self.model.withDrawMoney = textfiled.text;
        //根据提现金额 算手续费
        CGFloat fee = [money floatValue] *self.model.fee_rate;
        if (self.model.fee_min == 0) {
            self.model.handlingfee = [UIToolsControl showAmount:[NSString stringWithFormat:@"%.2f",fee]];
        }else{
            if (fee < self.model.fee_min) {
                //小于最小手续费的时候显示最小手续费
                self.model.handlingfee = [UIToolsControl showAmount:[NSString stringWithFormat:@"%.2f",self.model.fee_min]];
            }else if(fee > self.model.fee_max){
                self.model.handlingfee = [UIToolsControl showAmount:[NSString stringWithFormat:@"%.2f",self.model.fee_max]];
            }else{
                self.model.handlingfee = [UIToolsControl showAmount:[NSString stringWithFormat:@"%.2f",fee]];
            }
        }
        
        if (money.length == 0) {
            self.model.handlingfee = @"0";
        }

        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:self.model.handlingfee];
        NSAttributedString *strq = [[NSAttributedString alloc] initWithString:@"元" attributes:@{NSForegroundColorAttributeName :RGB(34, 34, 34),NSFontAttributeName : [UIFont systemFontOfSize:13]}];
        [str appendAttributedString:strq];
        self.handfeeLabel.attributedText = str;
        
        //实际提现金额
        
        CGFloat arrivemoney =  [money floatValue] - [self.model.handlingfee floatValue];
        if (arrivemoney < 0) {
            arrivemoney = 0;
        }
        self.model.arrival = [UIToolsControl showAmount:[NSString stringWithFormat:@"%.2f",arrivemoney]];
        
        NSMutableAttributedString *arrivalstr = [[NSMutableAttributedString alloc] initWithString:self.model.arrival];
        NSAttributedString *arrivalq = [[NSAttributedString alloc] initWithString:@"元" attributes:@{NSForegroundColorAttributeName :RGB(34, 34, 34),NSFontAttributeName : [UIFont systemFontOfSize:13]}];
        [arrivalstr appendAttributedString:arrivalq];
        self.arrivalLabel.attributedText = arrivalstr;
    }
}

- (void)applybuttonClick:(UIButton *)button{
    [self.view endEditing:YES];
    if (self.model.account.length ==0) {
        SVPHUDError(@"提现账户不能为空");
        return;
    }
    
    if (self.model.accountName.length == 0) {
        SVPHUDError(@"提现账户名不能为空");
        return;
    }
    
    if (self.model.withDrawMoney.length == 0) {
        SVPHUDError(@"提现金额不能为空");
        return;
    }
    
    CGFloat money = [self.model.withDrawMoney floatValue];
    if(money > [self.model.amount floatValue]) {
        SVPHUDError(@"提现金额不能大于余额");
        return;
    }
    
    if (self.model.amount_min != 0 && money < self.model.amount_min) {
        NSString *str = [NSString stringWithFormat:@"提现金额不能小于%.2f",self.model.amount_min];
        SVPHUDError(str);
        return;
    }
    
    if (self.model.amount_max != 0 && money > self.model.amount_max) {
        NSString *str = [NSString stringWithFormat:@"本次提现金额不能大于%.2f",self.model.amount_max];
        SVPHUDError(str);
        return;
    }
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    dic[@"payment"] = self.model.accountType;
    dic[@"bank_address"] = @"";
    dic[@"amount"] = [NSNumber numberWithFloat:[self.model.withDrawMoney floatValue]];
    dic[@"account"] = self.model.account;
    dic[@"account_name"] = self.model.accountName;
    __weak typeof(self) weakSelf = self;
    [BaseNetManager requestWithMethod:POST path:Wallet_withdraw_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            SVPHUDSuccess(@"提现成功");
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
        }else{
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}

- (void)checkBtnClick:(UIButton *)button{
    LYWithDrawListController *listVC = [[LYWithDrawListController alloc] init];
    [self.navigationController pushViewController:listVC animated:YES];
}


@end
